#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''Prepare PostgreSQL DBMS for labman2 by deleting existing db and user
   and making new ones.
   Reworked from a shell script used earlier.
'''

#   You need to change DIR to labman2 base directory.

#cmddir=`dirname $0`
#dumpfile=labman2_`date "+%Y%m%d"`.dump

#echo "sudo -u www pg_dump labman2 > $dumpfile"
#sudo -u www pg_dump labman2 > $dumpfile

#sudo -u pgsql dropdb labman2
#sudo -u pgsql dropuser www

#$cmddir/install.sh $@

## From file install.sh:
#DIR=~/progs/labman2
#cd $DIR

##sudo -u pgsql dropdb labman2
##sudo -u pgsql dropuser www
#sudo -u pgsql createuser -d -S -l -R www || {
#  echo "User exists. Use reinstall.sh to reinstall"
#  exit 1
#}
#sudo -u pgsql createdb labman2 || {
#  echo "Database exists. Use reinstall.sh to reinstall"
#  exit 1
#}

#./manage.py syncdb

#==========================================================

from optparse import OptionParser
import os
import platform
import subprocess
import sys
import time
from labman2.settings import DATABASES
#import subprocess
#import glob

class Labman2Install(object):
    "Collect all data and procedures for installing and reinstalling labman2"

    def __init__(self):
        self.debug = 0
        self.opts = None

    def log(self, message, level=1):
        "Print out a message with timestamp"
        if level <= self.debug:
            timestamp = time.strftime("%Y%m%d.%H:%M:%S", time.gmtime())
            print "%s %d: %s" % (timestamp, level, message)

    def setup(self):
        "Get arguments and options from config and command line"
        self.log("setup() called")
        parser = OptionParser()
        parser.add_option("-r", "--reinstall", dest="reinstall",
                        action="store_true",
                        help="Reinstall an existing labman2")
        parser.add_option("-b", "--basedir", dest="basedir", metavar="DIR",
                        default=os.getcwdu(),
                        help="Specify the base directory of labman2. "
                             "Default: current working directory.")
        parser.add_option("-d", "--dumpdir", dest="dumpdir", metavar="DIR",
                        default=u"",
                        help="Save a dump of database in directory DIR. "
                             "Absolute path if starting with / or relative to "
                             "the base directory. Default: base directory.")
        parser.add_option("-D", "--debug", default=0, metavar="LEVEL",
                          dest="debug", help="set debug level to LEVEL")

        opts, args = parser.parse_args()
        # Check and normalize the options
        self.log(str(opts)+"; "+str(args), 5)
        if args:
            parser.error("No argument expected, only options.")
        if opts.basedir.startswith(u"/"):
            opts.basedir = os.path.abspath(opts.basedir)
        else:
            opts.basedir = os.path.abspath(os.getcwdu()+opts.basedir)
        if opts.dumpdir.startswith(u"/"):
            opts.dumpdir = os.path.abspath(opts.dumpdir)
        else:
            opts.dumpdir = os.path.abspath(opts.basedir+opts.dumpdir)
        if opts.debug:
            self.debug = eval('int(%s)' % opts.debug)

        self.opts = opts

    def dump_db(self):
        "Dump an existing labman2 database before dropping it"
        self.log("dump_db() called " + str(self.opts))
#        self.log(os.name)
#        self.log(os.uname())
#        self.log(sys.platform)
#        self.log(platform.uname())
        timestamp = time.strftime("%Y%m%d.%H.%M.%S", time.gmtime())
        dumpfile = "%s/pg_dump.labman2.%s.sql" % (self.opts.dumpdir, timestamp)
        osname = os.uname()[0]
        print osname, dumpfile
        user = DATABASES['default']['USER']
        host = DATABASES['default']['HOST'] if DATABASES['default']['HOST'] \
                                            else 'localhost'
        database_list = subprocess.Popen(
            'echo "SELECT datname FROM pg_database" '
                '| psql -t -U %s -h %s template1' % (user, host),
            shell=True, stdout=subprocess.PIPE).stdout.readlines()
        self.log("database_list: "+str(database_list))

        cmd = "echo Error!"
        if osname in ("FreeBSD", "Linux",):
#            cmd = "pg_dump -U %s -Z 9 -f %s -F c %s" % (user,
#                                                        dumpfile, "labman2")
            cmd = "pg_dump -U %s -f %s %s" % (user, dumpfile, "labman2")
        elif osname in ("Windows",):
            cmd = '"c:\\program files\\postgresql\\8.1\\bin\\pg_dump"'
        self.log("command line: "+str(cmd))
        subprocess.call(cmd, shell = True)

    def drop_db(self):
        "Drop an existing labman2 database and corresponding roles"
        self.log("drop_db() called " + str(self.opts))

    def new_db(self):
        "Create labman2 database and related roles"
        self.log("new_db() called " + str(self.opts))

    def setup_rc(self):
        "Setup labman2 related environment variables in .bashrc"
        self.log("setup_rc() called " + str(self.opts))

    def sync_db(self):
        "Create labman2 database tables and setup initial data"
        self.log("sync_db() called " + str(self.opts))

    def main(self):
        "Install or re-install labman2"

        self.setup()
        if self.opts.reinstall:
            self.dump_db()
            self.drop_db()
            self.new_db()
        else:
            self.setup_rc()
        self.sync_db()

Labman2Install().main()
